package dom;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Test_Dom4j_Convert {
	
	public static void main(String[] args) {
		Test_Dom4j_Convert.StringtoXml();
		
		//Test_Dom4j_Convert.XmltoString();
		
	}


	/**
	 * 把String 转为  xml对象
	 */
	private static void StringtoXml() {
		String xml_str="<root><name>admin</name><age>21</age></root>";
		
		try {
			Document document=DocumentHelper.parseText(xml_str);
			Element rootElement=document.getRootElement();
			
			String name=rootElement.element("name").getText();
			String age=rootElement.elementText("age");
			
			System.out.println("name="+name+"\t age="+age);
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
	}
	
	
	private static void XmltoString() {
		File xmlFile=new File("./src/student.xml");
		
		SAXReader saxReader=new SAXReader();
		
		try {
			Document document=saxReader.read(xmlFile);
			
			Element rootElement=document.getRootElement();
			
			Element parenElement=(Element)rootElement.elements("root").get(0);
			
			String xmltoString=parenElement.asXML();
			
			System.out.println(xmltoString);
			
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		
			
		
	}

	
	
}
